package com.sayice.robotconflict.view.page

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.ColorPainter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.sayice.robotconflict.model.Message
import com.sayice.robotconflict.model.receive.PlayerInfo
import com.sayice.robotconflict.model.receive.TeamInviteInfo
import com.sayice.robotconflict.model.send.MatchInfo
import com.sayice.robotconflict.ui.screen.cdp
import com.sayice.robotconflict.ui.screen.csp
import com.sayice.robotconflict.util.unread
import com.sayice.robotconflict.view.route.Route
import com.sayice.robotconflict.viewmodel.GameViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 游戏大厅页面
 */
@Composable
fun Hall(viewModel: GameViewModel) {
    val scope = rememberCoroutineScope()
    val friendReqsState by viewModel.friendReqsFlow.collectAsState()
    val unreadFriendReqs by derivedStateOf { friendReqsState.filter { !it.read } }
    var teamInviteInfo by remember { mutableStateOf<TeamInviteInfo?>(null) }
    var openRankingDialog by remember { mutableStateOf(false) }
    val teamSizes = listOf(1, 3, 5)
    val teamRoomMaxSizes = listOf(3, 5)
    LaunchedEffect(Unit) {
        // 获取好友申请信息
        viewModel.sendToServer(Message(type = "social", action = "getFriendReqs"))
        // 收集组队邀请信息
        viewModel.teamInviteInfoFlow.collect {
            teamInviteInfo = it
        }
    }
    Box(modifier = Modifier.fillMaxSize()) {
        Row(modifier = Modifier.align(Alignment.TopStart)) {
            // 个人中心入口
            Button(onClick = { viewModel.goToPage(Route.PLAYER_CENTER) }) {
                Text("个人中心")
            }
            // 好友管理页面入口
            Button(
                onClick = { viewModel.goToPage(Route.FRIENDS) },
                modifier = Modifier.unread(show = unreadFriendReqs.isNotEmpty())
            ) {
                Text("好友")
            }
        }
        // 排行榜入口
        OutlinedButton(
            onClick = { openRankingDialog = true }, modifier = Modifier
                .defaultMinSize(1.dp, 1.dp)
                .align(Alignment.TopEnd),
            contentPadding = PaddingValues(horizontal = 10.cdp, vertical = 2.cdp)
        ) {
            Text(text = "排行榜", fontSize = 30.csp)
        }
        // 匹配入口
        Row(modifier = Modifier.align(Alignment.Center)) {
            var expandTeamMenu by remember { mutableStateOf(false) }
            var openRoomJoinDialog by remember { mutableStateOf(false) }
            for (teamSize in teamSizes) {
                Button(onClick = {
                    scope.launch(Dispatchers.IO) {
                        viewModel.sendToServer(
                            Message(
                                type = "match",
                                action = "start",
                                data = MatchInfo(type = "single", teamSize = teamSize)
                            )
                        )
                    }
                }) {
                    Text("${teamSize}v${teamSize}")
                }
            }
            Button(onClick = { expandTeamMenu = true }) {
                Text("组队")
            }
            DropdownMenu(expanded = expandTeamMenu, onDismissRequest = { expandTeamMenu = false }) {
                for (maxSize in teamRoomMaxSizes) {
                    DropdownMenuItem(onClick = {
                        scope.launch(Dispatchers.IO) {
                            viewModel.sendToServer(
                                Message(type = "team", action = "create", data = maxSize)
                            )
                            viewModel.goToPage(Route.TEAM_ROOM)
                            expandTeamMenu = false
                        }
                    }) {
                        Text("创建${maxSize}v${maxSize}房间")
                    }
                }
                DropdownMenuItem(onClick = { openRoomJoinDialog = true }) {
                    Text("加入房间")
                }
            }
            if (openRoomJoinDialog) {
                RoomJoinDialog(
                    onDismissRequest = { openRoomJoinDialog = false },
                    onFinish = { openRoomJoinDialog = false },
                    viewModel = viewModel
                )
            }
        }
        // 组队邀请确认框
        if (teamInviteInfo != null) {
            TeamInviteAlertDialog(
                teamInviteInfo = teamInviteInfo!!,
                onDismissRequest = { teamInviteInfo = null },
                onFinish = { teamInviteInfo = null },
                viewModel = viewModel
            )
        }
        // 排行榜弹框
        if (openRankingDialog) {
            RankingDialog(viewModel = viewModel, onDismissRequest = { openRankingDialog = false })
        }
    }
}

/**
 * 确认框-组队邀请
 *
 * @param teamInviteInfo 组队邀请信息
 * @param onDismissRequest 对话框关闭回调
 * @param onFinish 操作完成回调
 * @param viewModel ViewModel
 */
@Composable
fun TeamInviteAlertDialog(
    teamInviteInfo: TeamInviteInfo,
    onDismissRequest: () -> Unit,
    onFinish: () -> Unit,
    viewModel: GameViewModel
) {
    val scope = rememberCoroutineScope()
    AlertDialog(
        onDismissRequest = {
            onDismissRequest()
            viewModel.clearTeamInviteInfo()
        },
        title = { Text("${teamInviteInfo.playerName}邀请你组队") },
        confirmButton = {
            TextButton(onClick = {
                scope.launch(Dispatchers.IO) {
                    viewModel.sendToServer(
                        Message(
                            type = "team",
                            action = "join",
                            data = teamInviteInfo.roomId
                        )
                    )
                    onFinish()
                    viewModel.clearTeamInviteInfo()
                }
            }) {
                Text("加入")
            }
        },
        dismissButton = {
            TextButton(onClick = {
                onFinish()
                viewModel.clearTeamInviteInfo()
            }) {
                Text("忽略")
            }
        }
    )
}

/**
 * 弹框-排行榜
 *
 * @param onDismissRequest 对话框关闭回调
 * @param viewModel ViewModel
 */
@Composable
fun RankingDialog(onDismissRequest: () -> Unit, viewModel: GameViewModel) {
    val rankingState by viewModel.rankingFlow.collectAsState()
    LaunchedEffect(Unit) {
        // 获取排行榜
        viewModel.sendToServer(Message(type = "player", action = "ranking"))
    }
    Dialog(onDismissRequest = onDismissRequest) {
        LazyColumn(
            modifier = Modifier
                .size(width = 1800.cdp, height = 1000.cdp)
                .background(Color.White),
            contentPadding = PaddingValues(10.cdp),
            verticalArrangement = Arrangement.spacedBy(10.cdp)
        ) {
            itemsIndexed(rankingState) { index, playerInfo ->
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text("${index + 1}")
                    Spacer(modifier = Modifier.width(50.cdp))
                    RankingPlayer(playerInfo)
                }
            }
        }
    }
}

/**
 * 弹框-加入房间
 *
 * @param onDismissRequest 对话框关闭回调
 * @param onFinish 操作完成回调
 * @param viewModel ViewModel
 */
@Composable
fun RoomJoinDialog(onDismissRequest: () -> Unit, onFinish: () -> Unit, viewModel: GameViewModel) {
    val scope = rememberCoroutineScope()
    var roomId by rememberSaveable { mutableStateOf("") }
    Dialog(onDismissRequest = onDismissRequest) {
        Row(
            modifier = Modifier
                .background(Color.White)
                .padding(10.cdp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            TextField(
                value = roomId,
                onValueChange = { roomId = it },
                modifier = Modifier.width(600.cdp),
                placeholder = { Text("房间号") }
            )
            Spacer(modifier = Modifier.width(10.cdp))
            Button(onClick = {
                scope.launch(Dispatchers.IO) {
                    viewModel.sendToServer(
                        Message(
                            type = "team",
                            action = "join",
                            data = roomId.toIntOrNull() ?: -1
                        )
                    )
                    onFinish()
                }
            }, modifier = Modifier.width(200.cdp)) {
                Text("加入")
            }
        }
    }
}

/**
 * 排行榜玩家
 *
 * @param playerInfo 玩家信息
 */
@Composable
private fun RankingPlayer(playerInfo: PlayerInfo) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Image(
            painter = ColorPainter(Color.Blue), contentDescription = null,
            modifier = Modifier
                .clip(CircleShape)
                .size(80.cdp)
        )
        Spacer(modifier = Modifier.width(50.cdp))
        Text(playerInfo.name)
        Spacer(modifier = Modifier.width(50.cdp))
        Text("胜率: ${playerInfo.winRate}%")
    }
}